#!/usr/bin/bash
#
#  Usage: 自定义服务器SSL证书
#  Issue: 2024-05-17
# Author: Leon Hsia
#   Mail: waxwork3@163.com
#
base_path=$(dirname $(realpath $0))
cd $base_path

cd $base_path/pki
sed -i '/^DNS/d' ssl.cnf 
sed -i '/^IP/d' ssl.cnf 
cat ../nginx/conf.d/*.conf \
|grep server_name \
|tr -d ';' \
|awk '{print $2}' \
|grep -v localhost \
|awk -F. 'BEGIN{OFS="."}{$1="*";print}' \
|sort |uniq |awk '{i++;print "DNS."i" = "$0}' >>ssl.cnf
ip ro get 8.8.8.8 |grep -oP '\d+\.\d+\.\d+\.\d+' |awk 'END{print "DNS.249 = "$1}' >>ssl.cnf
ip ro get 8.8.8.8 |grep -oP '\d+\.\d+\.\d+\.\d+' |awk 'END{print "IP.249= "$1}' >>ssl.cnf
openssl req -new -sha256 -utf8 -config ssl.cnf -newkey rsa:2048 -nodes -keyout server.key -out server.csr 2>/dev/null
faketime 'last friday' openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 396 -extensions 'v3_req' -extfile ./ssl.cnf 2>/dev/null
openssl x509 -text -noout -in server.crt |sed '/Modulus/,/Exponent/d;/Value:/,$d'

\cp server.* ../nginx
